package de.sr.gwtdemo.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

import de.sr.gwtdemo.client.service.UserService;
import de.sr.gwtdemo.client.service.UserServiceAsync;
import de.sr.gwtdemo.client.widgets.busybox.BusyBox;
import de.sr.gwtdemo.client.widgets.console.Console;
import de.sr.gwtdemo.client.widgets.console.UiLogger;
import de.sr.gwtdemo.client.widgets.console.UiLogger.Level;
import de.sr.gwtdemo.shared.model.User;

public class Index implements EntryPoint, KeyDownHandler, KeyPressHandler {

	private static final UiLogger LOG = UiLogger.create(Index.class);
	private static final Level LOG_LEVEL = Level.DEBUG;
	private Console console = Console.getInstance();

	private UserServiceAsync userService = GWT.create(UserService.class);

	public void onModuleLoad() {
		initLogger();
		initBusyBox();

		FocusPanel sp = new FocusPanel();
		sp.add(new Label("it works!"));
		RootPanel.get("content").add(sp);
		
		BusyBox.getInstance().setLoaderMessage("Initializing User...");
		initUser();
	}

	private void initUser() {
		userService.getActualUser(new AsyncCallback<User>() {
			public void onSuccess(User user) {
				BusyBox.getInstance().setLoaderMessage("");
				RootPanel.get().add(new Label("User is: " + user.getName()));
			}
			public void onFailure(Throwable throwable) {
				BusyBox.getInstance().setLoaderMessage("");
				LOG.error("Failed to get user: ", throwable);
			}
		});
	}

	private void initBusyBox() {
		RootPanel.get().add(BusyBox.getInstance());
	}

	private void initLogger() {
		BusyBox.getInstance().setLoaderMessage("Initializing Logger...");
		UiLogger.setLogLevel(LOG_LEVEL);
		RootPanel.get().add(console);
		BusyBox.getInstance().setLoaderMessage("");
		// console.setVisible(false);
	}

	public void onKeyDown(KeyDownEvent event) {
		LOG.debug("Key down: " + event.getNativeKeyCode());

	}

	public void onKeyPress(KeyPressEvent event) {
		LOG.debug("Key press: " + event.getUnicodeCharCode());

	}

}
